package com.wgke.bluetooth.vm;

import android.text.TextUtils;
import android.util.Log;

import androidx.lifecycle.MutableLiveData;

import com.wgke.bluetooth.beans.CommandBean;
import com.wgke.bluetooth.beans.CommandGroup;
import com.wgke.bluetooth.db.CmdEntity;
import com.wgke.bluetooth.utils.CommonUtil;
import com.wgke.bluetooth.utils.SpUtil;

import java.util.Arrays;
import java.util.List;

public class RWVM extends ReadWriteVM {

    public MutableLiveData<List<CommandBean>> mList = new MutableLiveData<>();

    public void loadFileRes() {
        mList.postValue(CommandGroup.getInstance().getBody());
    }

    public String getCmd(CommandBean bean) {
        return getCmd(bean, null);
    }

    public String getCmd(CommandBean bean, int value) {
        return getCmd(bean, new int[]{value});
    }

    public String getCmd(CommandBean bean, int[] value) {
        String hexStr = CommandGroup.getInstance().getCmd(bean, value);
        String cleanHex = hexStr.replaceAll("[^0-9a-fA-F]", "");
        return cleanHex.replaceAll("(.{2})", "$1 ").trim();
    }

    public int[] rangeStringToIntArray(String rangeStr) {
        return CommonUtil.rangeStringToIntArray(rangeStr);
    }

    String lastText = "";
    long lastTime=0;

    @Override
    public void readBytes(boolean isRead, byte[] data) {
        StringBuilder hexString = new StringBuilder();
        for (byte b : data) {
            hexString.append(String.format("%02X ", b));
        }
        Log.e("ReadWriteVM", "readBytes: " + hexString);
        count++;
        if (count > 99) count = 1;
        long time=System.currentTimeMillis();
        if (TextUtils.isEmpty(lastText)) {
            content.setValue(hexString.toString());
        } else{
            if(Math.abs(time-lastTime)<100){
                content.setValue(lastText + hexString);
            }else{
                content.setValue(hexString.toString());
            }
        }
        lastText = hexString.toString();
        lastTime=time;
        readCount.setValue(count);
    }
}
